/**
 * Copyright (C) 2017 - 2020 https://github.com/joewee
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bifrost.repository;

import com.bifrost.entity.Category;
import com.bifrost.entity.Product;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * @author joewee
 * @version 1.0.0
 * @Date 2017/10/25 19:45
 */
public interface ProductRepository extends JpaRepository<Product, Long>, JpaSpecificationExecutor<Product> {

    /**
     * 查询目录下的所有商品
     * @param productCategory
     * @return
     */
    @Query("select p from Product as p left join fetch p.defaultSku  where p.productCategory =?1")
    List<Product> findAllByProductCategoryOrderBySortOrder(Category productCategory);

    @Transactional
    @Modifying
    @Query(value = " UPDATE Product p SET p.available=?2 WHERE p.productId IN (?1)")
    void updateProduct(Collection ids, Boolean available);


    @Query(nativeQuery = true , value = "SELECT count(1) FROM product WHERE CATEGORY=?1 AND IS_ARCHIVED=?2")
    Long countAllByIsArchivedByCate(Long categoryId , Boolean flag);

    Product findFirstByExternalId(String externalId);

    @Transactional
    @Modifying
    @Query(value = " UPDATE Product p SET p.available=?4 , p.auditStatus=?2 ,p.updatedTimestamp=?3 WHERE p.productId IN (?1)")
    void updateProduct(Collection ids, String auditStatus, Date updatedTimestamp,Boolean available);


    @Transactional
    @Modifying
    @Query(value = " UPDATE Product p SET p.featuredProduct=?2,p.updatedTimestamp=?3 WHERE p.productId IN (?1)")
    void batchUpdateFeature(Collection ids, Boolean featuredProduct,Date updatedTimestamp);

    Product findFirstByMerchantIdAndExternalId(Long merchantId, String externalId);

    List<Product> findAllByExternalCcategoryLike(String code);

    @Transactional
    @Modifying(clearAutomatically = true)
    @Query(value = " UPDATE Product p SET p.externalCcategory=?2 WHERE p.productId = ?1")
    void updateCategoryCode(Long productId, String code);
}
